<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import userApi, { type UserProfile, type UpdateUserProfileDto } from "@/api/user";
import { useApartmentUserStoreHook } from "@/store/modules/apartmentUser";

defineOptions({
  name: "User"
});

// Get apartment user store
const apartmentUserStore = useApartmentUserStoreHook();

// User data from API
const userInfo = ref<UserProfile>({
  id: "",
  name: "",
  nickname: "",
  email: "",
  avatarUrl: "",
  level: "免费用户",
  expirationDate: ""
});

// Loading state
const loading = ref(false);

// Allow user to edit information
const isEditing = ref(false);
const formData = ref<UpdateUserProfileDto>({});

// Fetch user data on component mount
onMounted(async () => {
  try {
    loading.value = true;
    try {
      // Use the getCurrentUserProfile function which handles store interaction internally
      const data = await userApi.getCurrentUserProfile();
      userInfo.value = data;
    } catch (error) {
      console.error("Failed to fetch user profile, please make sure the backend is running and the test user exists");
      ElMessage.error("获取用户信息失败，请确保后端服务运行正常并且测试用户已创建");
    }
  } catch (error) {
    ElMessage.error("获取用户信息失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
});

const startEditing = () => {
  formData.value = {
    name: userInfo.value.name,
    nickname: userInfo.value.nickname,
    email: userInfo.value.email,
    avatarUrl: userInfo.value.avatarUrl
  };
  isEditing.value = true;
};

const cancelEditing = () => {
  isEditing.value = false;
};

const saveUserInfo = async () => {
  try {
    loading.value = true;
    const userId = userInfo.value.id;
    const updatedUser = await userApi.updateUserProfile(userId, formData.value);
    userInfo.value = updatedUser;
    isEditing.value = false;
    ElMessage.success("用户信息已更新");
  } catch (error) {
    ElMessage.error("更新用户信息失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// Handle recharge click event
const handleRecharge = () => {
  ElMessage.info("充值功能即将上线，敬请期待！");
  // Here you can add actual recharge logic, such as redirecting to payment page or opening a recharge popup
};
</script>

<template>
  <div class="user-profile-container">
    <div class="user-profile-card">
      <div class="card-header">
        <h1>用户个人信息</h1>
        <div class="actions">
          <el-button v-if="!isEditing" type="primary" @click="startEditing">
            编辑
          </el-button>
          <template v-else>
            <el-button @click="cancelEditing">取消</el-button>
            <el-button type="primary" @click="saveUserInfo">保存</el-button>
          </template>
        </div>
      </div>

      <div class="user-info-content">
        <div class="avatar-section">
          <el-avatar :size="120" :src="userInfo.avatarUrl" />
          <div v-if="isEditing" class="avatar-upload">
            <el-upload
              class="avatar-uploader"
              action="#"
              :auto-upload="false"
              :show-file-list="false"
            >
              <el-button size="small" type="primary">更换头像</el-button>
            </el-upload>
          </div>
        </div>

        <div class="user-details">
          <div v-if="!isEditing" class="info-display">
            <div class="info-item">
              <div class="label">用户名字</div>
              <div class="value">{{ userInfo.name }}</div>
            </div>
            <div class="info-item">
              <div class="label">用户昵称</div>
              <div class="value">{{ userInfo.nickname }}</div>
            </div>
            <div class="info-item">
              <div class="label">电子邮箱</div>
              <div class="value">{{ userInfo.email }}</div>
            </div>
            <div class="info-item">
              <div class="label">用户等级</div>
              <div class="value membership-level">
                <span :class="['level-tag', 
                  userInfo.level === '免费用户' ? 'free' : 
                  userInfo.level === '月费用户' ? 'monthly' : 'pro'
                ]">{{ userInfo.level }}</span>
                <el-button type="success" size="small" @click="handleRecharge">充值</el-button>
              </div>
            </div>
            <div class="info-item">
              <div class="label">等级过期时间</div>
              <div class="value">{{ userInfo.expirationDate }}</div>
            </div>
          </div>

          <el-form v-else label-position="top" class="edit-form">
            <el-form-item label="用户名字">
              <el-input v-model="formData.name" placeholder="请输入用户名字" />
            </el-form-item>
            <el-form-item label="用户昵称">
              <el-input v-model="formData.nickname" placeholder="请输入用户昵称" />
            </el-form-item>
            <el-form-item label="电子邮箱">
              <el-input v-model="formData.email" placeholder="请输入电子邮箱" />
            </el-form-item>
            <el-form-item label="用户等级">
              <div class="readonly-field">
                <span :class="['level-tag', 
                  userInfo.level === '免费用户' ? 'free' : 
                  userInfo.level === '月费用户' ? 'monthly' : 'pro'
                ]">{{ userInfo.level }}</span>
                <el-button type="success" size="small" @click="handleRecharge">充值</el-button>
              </div>
            </el-form-item>
            <el-form-item label="等级过期时间">
              <div class="readonly-field">{{ userInfo.expirationDate }}</div>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.user-profile-container {
  padding: 20px 30px 20px 30px;
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  
  .user-profile-card {
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    overflow: hidden;
    width: 100%;
    max-width: 1000px; // 限制最大宽度，保证两侧有间距
    
    .card-header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      
      h1 {
        margin: 0;
        font-size: 20px;
        color: #303133;
        font-weight: 500;
      }
      
      .actions {
        display: flex;
        gap: 12px;
        margin-top: 8px;
      }
      
      @media (max-width: 480px) {
        flex-direction: column;
        align-items: flex-start;
        
        .actions {
          margin-top: 16px;
          align-self: flex-end;
        }
      }
    }
    
    .user-info-content {
      padding: 32px;
      display: flex;
      
      @media (max-width: 768px) {
        flex-direction: column;
        align-items: center;
        padding: 24px 16px;
      }
      
      .avatar-section {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 48px;
        
        @media (max-width: 768px) {
          margin-right: 0;
          margin-bottom: 24px;
        }
        
        .avatar-upload {
          margin-top: 16px;
        }
      }
      
      .user-details {
        flex: 1;
        width: 100%;
        
        @media (max-width: 768px) {
          width: 100%;
        }
        
        .info-display {
          .info-item {
            margin-bottom: 24px;
            word-break: break-word;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .label {
              font-size: 14px;
              color: #909399;
              margin-bottom: 8px;
            }
            
            .value {
              font-size: 16px;
              color: #303133;
              font-weight: 500;
              
              &.membership-level {
                display: flex;
                align-items: center;
                gap: 12px;
              }
            }
          }
        }
        
        .edit-form {
          max-width: 400px;
          width: 100%;
          
          @media (max-width: 480px) {
            max-width: 100%;
          }
          
          .readonly-field {
            font-size: 16px;
            color: #303133;
            padding: 8px 0;
            display: flex;
            align-items: center;
            gap: 12px;
          }
        }
        
        .level-tag {
          display: inline-block;
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 14px;
          font-weight: 500;
          
          &.free {
            background-color: #e6e6e6;
            color: #606266;
          }
          
          &.monthly {
            background-color: #ecf5ff;
            color: #409eff;
          }
          
          &.pro {
            background-color: #f0f9eb;
            color: #67c23a;
          }
        }
      }
    }
  }
}
</style>
